package cn.tedu.csmall.passport.security;
 /*
 @Time: 2022/9/8 9:24
 @Author:GShuai
 @File:DetailServiceImpl.class
 @Software:IntelliJ IDEA
*/


import cn.tedu.csmall.passport.mapper.AdminMapper;
import cn.tedu.csmall.passport.pojo.vo.AdminLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;

    void UserDetailsServiceImpl() {
        log.debug("创建Security框架自动调用的UserDetailsService实现类对象：UserDetailsServiceImpl");
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security 自动根据用户名【{}】查询用户详情", s);
        // 执行查询
        AdminLoginVO admin = adminMapper.getByUsername(s);
        // 判断是否查询到有效结果
        if (admin != null) {
            log.debug("查询到匹配管理员信息：{}", admin);

            List<String> permissions = admin.getPermissions();
            List<SimpleGrantedAuthority> authorities =new ArrayList<>();
            for (String permission : permissions) {
                authorities.add(new SimpleGrantedAuthority(permission));
            }
            AdminDetails adminDetails = new AdminDetails(
                    admin.getUsername(),
                    admin.getPassword(),
                    admin.getEnable() == 1,
                    authorities
            );
            adminDetails.setId(admin.getId());
            log.debug("即将向Spring Security返回adminDetails：{}", adminDetails);
            return adminDetails;
        }
        log.debug("没有查询到匹配的管理员信息！");
        return null;
    }
}
